/*
 * Copyright (C) 2010 Fred Barrie This program is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version. This program is distributed
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details. You should have received
 * a copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
package org.aergia.vinny.gui.util;

import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JTextField;

/**
 * @author Fred
 */
public class TextField extends JTextField implements FocusListener, KeyListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3142409940713783295L;

	public TextField() {
		super();
		this.initComponent();
	}

	public TextField(final String text) {
		super(text != null ? text : "");
		this.initComponent();
	}

	@Override
	public void focusGained(final FocusEvent e) {
		this.setSelectionStart(0);
		this.setSelectionEnd(this.getText().length());
	}

	@Override
	public void focusLost(final FocusEvent e) {
		this.setSelectionStart(0);
		this.setSelectionEnd(0);
		this.updateForegroundColor();
	}

	@Override
	public void keyPressed(final KeyEvent arg0) {
		// ignore
	}

	@Override
	public void keyReleased(final KeyEvent arg0) {
		this.updateForegroundColor();
	}

	@Override
	public void keyTyped(final KeyEvent arg0) {
		// ignore;
	}

	protected void updateForegroundColor() {
		this.setForeground(this.verify() ? Color.BLACK : Color.RED);
	}

	protected boolean verify() {
		return true;
	}

	private void initComponent() {
		this.addFocusListener(this);
		this.addKeyListener(this);
		this.setColumns(20);
	}
}
